package com.dcits.electronic_account.utils;

import com.dcits.electronic_account.bean.VerificationCode;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import static com.dcits.electronic_account.utils.DateStampUtil.dateToString;

/**
 * @Author: CZJ
 * @Date： 2022/6/26
 */
public class VerificationCodeUtil {

    private static HashMap<String, VerificationCode> verificationCode = new HashMap<>();

    /**
     * @func 在控制台生成验证码函数
     * @param phone
     * @return
     */
    public static String generateVerificationCode(String phone) {
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        String code = sb.toString();

        // 在map中保存验证码信息
        VerificationCode temp = new VerificationCode();
        temp.setPhone(phone);
        temp.setCode(code);
        Date date = new Date();
        temp.setGenerateTime(dateToString(date));
        temp.setValidTime(dateToString(new Date(date.getTime() + 60000)));
        verificationCode.put(phone, temp);

        return code;
    }

    /**
     * @func 判断验证码是否正确且有效
     * @param phone
     * @param code
     * @return
     */
    public static boolean verificationCodeValidate(String phone, String code){
        if (verificationCode.containsKey(phone)){
            if (verificationCode.get(phone).getCode().equals(code) && verificationCode.get(phone).getValidTime().compareTo(dateToString(new Date())) >= 0){
                verificationCode.remove(phone);
                return true;
            }
            verificationCode.remove(phone);
            return false;
        }
        return false;
    }

    /**
     * func 判断验证码是否已存在
     * @param phone
     * @return
     */
    public static boolean verificationCodeExist(String phone){
        if (verificationCode.containsKey(phone)) {
            if (verificationCode.get(phone).getValidTime().compareTo(dateToString(new Date())) < 0){
                verificationCode.remove(phone);
                return false;
            }
            return true;
        }
        return false;
    }
}
